package com.springboot.controller;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.model.po.Coupon;
//import com.springboot.model.po.Orders;
import com.springboot.model.po.UserCoupon;
import com.springboot.service.UserCouponService;

import util.UserCouponUtil;
import util.VerifyUtil;

@RefreshScope	//监听动态刷新
@RequestMapping("/userCoupons")
@RestController
public class UserCouponController {
	@Autowired
	UserCouponService userCouponService;
	
	@GetMapping("/{userId}")
	public ResponseEntity listUserCoupon(@PathVariable String userId , @RequestParam String token) throws Exception{
		//根据用户id请求所持有优惠券typeId列表,'使用优惠券界面'使用
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		List<Integer> list = userCouponService.listUserCoupon(userId);
		if(list.size() == 0 || list == null) {
			return  ResponseEntity.status(HttpStatus.NOT_FOUND).body("The requested resource was not found.");
		}else {
			return ResponseEntity.ok(list);
		}
	}
	
	@GetMapping("/all/{userId}")
	public ResponseEntity listUserCouponAll(@PathVariable String userId , @RequestParam String token) throws Exception{
		//获取用户所拥有的所有优惠卷的信息
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		List<UserCoupon> list =  userCouponService.listUserCouponAll(userId);
		int label[] = {0 , 0 , 0 , 0 , 0 ,0 , 0 , 0 , 0 , 0 };
			for(UserCoupon u : list) {
				int typeId = u.getTypeId();
				if(label[typeId-1] == 0) {
					label[typeId-1] = 1;
				}
			}
			for(int a : label) {
				if(a == 0) {
					UserCoupon userCoupon = UserCouponUtil.filterNull(a+1, userId);
					list.add(userCoupon);
				};
			}
			return ResponseEntity.ok(list);
		}
		
		
	
	
	//先显示能够使用的券，有的话再调用下面的使用
	@GetMapping("/coupons")
	public ResponseEntity listUserCouponByOrderTotal(String userId , BigDecimal orderTotal , @RequestParam String token) throws Exception{
		//根据用户id请求以及订单金额显示可以使用的优惠券
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		List<UserCoupon> list = userCouponService.listUserCouponByOrderTotal(userId , orderTotal);
		int number = 0;
		for(UserCoupon usercoupon : list) {
			if(usercoupon.getCouponId() == 0)
				number++;
		}
		if (list == null || list.size() == 0 || number == 10){
				return ResponseEntity.status(HttpStatus.NO_CONTENT).body("No Content");//返回204，无内容。
		}else {
			return ResponseEntity.ok(list);
		}
	}
	
//	//先显示能够使用的券，有的话再调用下面的使用
//	@GetMapping("/hasUserCoupon")
//	public Integer hasUserCoupon(String userId , BigDecimal orderTotal) throws Exception{
//		//根据用户id请求以及订单金额显示是否有可用的优惠券
//		return userCouponService.hasUserCoupon(userId , orderTotal);
//	}
		

		
	//这个方法只是计算优惠后的订单价格而不是真正使用，使用优惠券在orderState那里（并且会删除优惠券）
	//出错的时候直接就会报错，不需要ResponseEntity包装
	@GetMapping("/orderTotal")
	public ResponseEntity useCoupon(Integer typeId , Integer orderId) throws Exception{
		//订单生成之后就会出现Id（createOrder返回值就是id）
		//只用于返回订单价格更新，支付之后才删除优惠券
		BigDecimal result = userCouponService.useCoupon(typeId, orderId);
		if(result.compareTo(BigDecimal.ZERO) == 0) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("OrderTotal can not less than usePrice of the coupon");
		}else {
			return ResponseEntity.ok(result);
		}
	}
	
	@GetMapping("/number")
	public ResponseEntity getUserCouponQuantity(Integer typeId , String userId , @RequestParam String token) throws Exception{
		//获取某个用户的某个优惠券的数量
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		Integer result = userCouponService.getUserCouponQuantity(userId , typeId);
		if(result == null) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No coupon available");
		}else
			return ResponseEntity.ok(result);
	}
	
	@PutMapping
	public ResponseEntity saveUserCoupon(@RequestBody UserCoupon userCoupon , @RequestParam String token) throws Exception{
		//购买优惠卷，输入用户编号和优惠券编号
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userCoupon.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		int result = userCouponService.saveUserCoupon(userCoupon.getUserId(), userCoupon.getTypeId());
		if(result == 1) {
			return ResponseEntity.ok("ok");
		}else {
			return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
	}
		
	@PutMapping("/{userId}/{typeId}")
	public ResponseEntity updateUserCounpon(@PathVariable("userId") String userId , @PathVariable("typeId") Integer typeId , @RequestParam("token") String token) throws Exception{
		//购买优惠卷，输入用户编号和优惠券编号
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !userId.equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		int result = userCouponService.updateUserCounpon(userId, typeId);
		if(result == 1) {
			return ResponseEntity.ok("ok");
		}else {
			return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}	
		

	}
	
	
	
}
